<template>
  <div class="app-container">
    <!-- 学年/学期 -->
    <!-- 这里的@selecrYear是接收timeSelect提交的事件 -->
    <time-select
      style="margin-top: 20px"
      ref="timeSelect"
      @selectYear="getList()"
      @selectSemester="getList()"
    ></time-select>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="" prop="userId">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程或班级名称"
          clearable
          size="big"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择预约状态"
          clearable
          size="big"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="big"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="big" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-dropdown style="margin-right: 10px" @command="handleCommand">
          <el-button type="primary" plain size="mini" :disabled="batchHandle()">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item icon="el-icon-check" command="1"
              >批量通过</el-dropdown-item
            >
            <el-dropdown-item icon="el-icon-close" command="2"
              >批量驳回</el-dropdown-item
            >
            <el-dropdown-item icon="el-icon-delete" command="3"
              >批量取消</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>

        <!-- <el-button
          type="info"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleCancel"
          :disabled="recordIdsSelection.length == 0"
          >批量取消</el-button
        > -->

        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="recordList.length == 0"
          >导出所有</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="recordTable"
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
        :selectable="selectable"
      />
      <el-table-column label="实验室地点" align="center" prop="location" />
      <el-table-column label="实验室名称" align="center" prop="labName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级人数" align="center" prop="number" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="预约时间" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.year }}-{{ scope.row.year + 1 }}学年</div>
          <div>第{{ scope.row.term + 1 }}学期</div>
          <div>周{{ scope.row.day }}第{{ scope.row.time }}节</div>
          <div>{{ scope.row.week }}</div>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="gmtModified" />
      <el-table-column
        label="预约状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
      >
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.status == 0">{{
            statusFormat(scope.row)
          }}</el-tag>
          <el-tag type="success" v-else-if="scope.row.status == 1">{{
            statusFormat(scope.row)
          }}</el-tag>
          <el-tag type="info" v-else-if="scope.row.status == 3">{{
            statusFormat(scope.row)
          }}</el-tag>
          <el-popover
            v-else
            placement="top-start"
            title="驳回内容："
            width="200"
            trigger="hover"
          >
            {{ scope.row.rejectContent }}
            <el-tag type="danger" slot="reference">{{
              statusFormat(scope.row)
            }}</el-tag>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="approveBook(scope.row)"
            :disabled="scope.row.status == 0 ? false : true"
            >审批</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="cancelBook(scope.row)"
            :disabled="scope.row.status == 1 ? false : true"
            >取消</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 驳回对话框 -->
    <el-dialog :visible.sync="rejectOpen" width="300px" append-to-body>
      <h3>驳回理由</h3>
      <el-input
        type="textarea"
        :rows="5"
        placeholder="请输入驳回内容"
        v-model="rejectContent"
      >
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="rejectBatch" v-if="rejectBatchFlag"
          >确 定</el-button
        >
        <el-button type="primary" @click="rejectBook" v-else>确 定</el-button>

        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批预约" :visible.sync="approveOpen" width="30%">
      <span>是否审批通过该条实验室预约记录</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectOpen = true">审批驳回</el-button>
        <el-button type="primary" @click="passBook">审批通过</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManagerRecord,
  exportRecord,
  managerCancel,
  approve,
} from "@/api/labbooking/record";
import Editor from "@/components/Editor";
import timeSelect from "@/views/components/timeSelect";

export default {
  name: "Record",
  components: {
    Editor,
    timeSelect,
  },
  data() {
    return {
      year: null,
      term: null,
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      rejectOpen: false,
      approveOpen: false,

      // 驳回内容
      rejectContent: null,
      // 标记是否为批量删除
      rejectBatchFlag: false,

      // 预约记录ID
      recordIdsSelection: [],
      // 取消信息
      cancelSelection: [],
      // 行记录
      rowRecordList: {},

      // 实验室预约信息表格数据
      recordList: [
        {
          location: "地点",
          labName: "实验室名称",
          className: "班级名称",
          number: 50,
          courseName: "课程名称",
          year: 2021,
          term: 0,
          day: 1,
          time: 1,
          week: "[1-18周]单",
          status: 0,
          gmtModified: "2021-05-07 11:11:11",
        },
      ],
      // 实验室预约状态[0-待审批, 1-审批通过, 2-驳回审批]字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        name: "",
        status: null,
        gmtModified: null,
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("lms_apply_status").then((response) => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询实验室预约信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      this.$nextTick(() => {
        this.year = this.$refs.timeSelect.year;
        this.term = this.$refs.timeSelect.semester;
        listManagerRecord({
          query: this.queryParams,
          name: this.queryParams.name,
          status: this.queryParams.status,
          year: this.year,
          term: this.term,
        }).then((response) => {
          this.recordList = response.rows;
          // console.log("预约信息：", this.recordList); //预约信息
          this.total = response.total;
          this.loading = false;
        });
      });
    },
    // 实验室预约状态[0-待审批, 1-审批通过, 2-驳回审批]字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeGmtCreate = [];
      this.daterangeGmtModified = [];
      this.queryParams = {};
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      const year = this.year;
      const term = this.term;
      this.$confirm("是否确认导出所有实验室预约信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportRecord({
            query: queryParams,
            year: year,
            term: term,
          });
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    cancel() {
      this.rejectOpen = false;
      this.rejectContent = "";
      this.rejectBatchFlag = false;
    },

    approveBook(row) {
      this.rowRecordList = row;
      this.approveOpen = true;
    },

    passBook() {
      this.$confirm("确认该条预约记录审批通过?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          approve([
            {
              userId: this.rowRecordList.userId,
              labId: this.rowRecordList.labId,
              status: 1,
              location: this.rowRecordList.location,
              labName: this.rowRecordList.labName,
              rejectContent: "",
              recordIdList: this.rowRecordList.recordIdList,
            },
          ]).then(() => {
            this.$message({
              type: "success",
              message: "审批通过",
            });
            this.approveOpen = false;
            this.rowRecordList = "";
            this.getList();
          });
        })
        .catch(() => {});
    },

    rejectBook() {
      approve([
        {
          userId: this.rowRecordList.userId,
          labId: this.rowRecordList.labId,
          status: 2,
          location: this.rowRecordList.location,
          labName: this.rowRecordList.labName,
          rejectContent: this.rejectContent,
          recordIdList: this.rowRecordList.recordIdList,
        },
      ]).then(() => {
        this.$message({
          type: "success",
          message: "驳回通过",
        });
        this.rejectContent = "";
        this.rowRecordList = {};
        this.rejectOpen = false;
        this.approveOpen = false;
        this.getList();
      });
    },

    cancelBook(row) {
      this.$confirm("是否取消该条实验室预约记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          managerCancel([
            {
              userId: row.userId,
              status: row.status,
              location: row.location,
              labName: row.labName,
              rejectContent: "",
              recordIdList: row.recordIdList,
            },
          ]).then(() => {
            this.$message({
              type: "success",
              message: "取消成功",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },

    batchHandle() {
      if (this.recordList.length == 0) {
        return true;
      } else if (this.recordIdsSelection.length == 0) {
        return true;
      } else if (this.cancelSelection.length == 0) {
        return true;
      }
      return false;
    },
    handleCommand(command) {
      if (command == "1") {
        this.changeStatus(1);
        this.approveBatch();
      } else if (command == "2") {
        this.changeStatus(2);
        this.rejectBatchFlag = true;
        this.rejectOpen = true;
      } else if (command == "3") {
        this.cancelBatch();
      }
    },
    changeStatus(status) {
      for (let i = 0; i < this.cancelSelection.length; i++) {
        var obj = this.cancelSelection[i];
        obj.status = status;
      }
    },
    changeRejctContent() {
      for (let i = 0; i < this.cancelSelection.length; i++) {
        var obj = this.cancelSelection[i];
        obj.rejectContent = this.rejectContent;
      }
    },
    approveBatch() {
      this.$confirm("是否批量通过实验室预约记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          approve(this.cancelSelection).then(() => {
            this.$message({
              type: "success",
              message: "审批通过",
            });
            this.rejectContent = "";
            this.rowRecordList = {};
            this.rejectOpen = false;
            this.getList();
          });
        })
        .catch(() => {});
    },
    rejectBatch() {
      this.changeRejctContent();
      this.$confirm("是否批量驳回取消实验室预约记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          approve(this.cancelSelection).then(
            () => {
              this.$message({
                type: "success",
                message: "驳回通过",
              });
              this.rejectContent = "";
              this.rowRecordList = {};
              this.rejectOpen = false;
              this.rejectBatchFlag = false;
              this.getList();
            },
            () => {
              this.rejectContent = "";
              this.rejectOpen = false;
              this.rejectBatchFlag = false;
            }
          );
        })

        .catch(() => {});
    },
    cancelBatch() {
      this.$confirm("是否批量取消实验室预约记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          managerCancel(this.cancelSelection).then(() => {
            this.$message({
              type: "success",
              message: "取消成功",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },

    handleSelectionChange(val) {
      this.recordIdsSelection = [];
      this.cancelSelection = [];
      for (let i = 0; i < val.length; i++) {
        this.recordIdsSelection.push(val[i].recordIdList[0]);
        var obj = {
          userId: val[i].userId,
          labId: val[i].labId,
          status: val[i].status,
          location: val[i].location,
          labName: val[i].labName,
          rejectContent: "",
          recordIdList: val[i].recordIdList,
        };
        this.cancelSelection.push(obj);
      }
    },
    selectable(row) {
      if (row.status == 2 || row.status == 3) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>
<style scoped>
.disvision >>> .el-input__inner {
  border: 0;
}
/* 如果你的 el-input type 设置成textarea ，就要用这个了 */
.disvision >>> .el-textarea__inner {
  border: 0;
  resize: none; /* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>